package tt.love.hw.service;

import java.io.UnsupportedEncodingException;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import tt.love.hw.email.EmailTemplate;
import tt.love.hw.exception.EmailSendException;
import tt.love.hw.jdo.User;

public class EmailService {

	public void send(User recipient, EmailTemplate template)
			throws EmailSendException {

		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress("licweiwei@gmail.com", "System"));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
					recipient.getEmail(), recipient.getUserName()));
			System.out.println(template.getSubject());
			System.out.println(template.getMsgBody());
			msg.setSubject(template.getSubject());
			msg.setText(template.getMsgBody());
			Transport.send(msg);

		} catch (AddressException e) {
			e.printStackTrace();
			throw new EmailSendException(e);
		} catch (MessagingException e) {
			e.printStackTrace();
			throw new EmailSendException(e);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new EmailSendException(e);

		}
	}

}
